<template>
	<el-container>
		<el-main>
		  <span v-if="isCustomer">
			  <span>&nbsp; 机构id: &nbsp; &nbsp;</span>
			  <el-select v-model="seachParms.CustomerID" style="margin-right: 10px" placeholder="请选择">
				  <el-option v-for="item in options" :key="item.ins_id" :label="item.ins_name" :value="item.ins_id">
				  </el-option>
			  </el-select>
		  </span>
			用户名称：
			<el-input v-model="seachParms.UserName" clearable placeholder="请输入用户名称"
				style="width: 200px; height: 40px; margin-right: 10px"></el-input>

			<el-button type="primary" @click="queryUserList(seachParms)">搜索</el-button>
			<el-button @click="setAddPop(true)">添加</el-button>

			<el-table v-loading="listLoading" :data="tableList" border stripe highlight-current-row
				style="width: 100%; margin: 20px 0 20px 0">
				<el-table-column label="机构名称" prop="AgentName" align="center">
					<template #default="scope">
						<span>{{ scope.row.AgentName }} </span>
					</template>
				</el-table-column>
				<el-table-column label="账号" prop="UserID" align="center" width="150">
					<template #default="scope">
						<span>{{ scope.row.UserID }}</span>
					</template>
				</el-table-column>
				<el-table-column label="用户名称" prop="UserName" align="center" width="150">
					<template #default="scope">
						<span>{{ scope.row.UserName }} </span>
					</template>
				</el-table-column>
				<el-table-column label="电话" prop="TelNo" align="center" width="150">
					<template #default="scope">
						<span>{{ scope.row.TelNo }} </span>
					</template>
				</el-table-column>
				<!-- <el-table-column label="机构id" prop="CustomerID" align="center">
					<template #default="scope">
						<span>{{ scope.row.CustomerID }} </span>
					</template>
				</el-table-column> -->
			
				<el-table-column label="邮箱" prop="Email" align="center">
					<template #default="scope">
						<span>{{ scope.row.Email }} </span>
					</template>
				</el-table-column>
				<el-table-column label="角色" prop="UserStatus" align="center" width="200">
					<template #default="scope">
						<span>{{ scope.row.RoleName }} </span>
					</template>
				</el-table-column>
				<el-table-column label="用户状态" prop="UserStatus" align="center" width="100">
					<template #default="scope">
						<span>{{ scope.row.UserStatus }} </span>
					</template>
				</el-table-column>
				<el-table-column align="center" label="设置" width="250">
					<!-- 修改 -->
					<template #default="{ row, column, $index }">
						<el-button size="small" text @click="setUpdatePop(true, row)">修改信息</el-button>
						<el-button size="small" text @click="setStatePop(true, row)">修改状态</el-button>
						<el-button size="small" text @click="deleteUser(row)">删除</el-button>
						<el-button size="small" text @click="setRolePop(true, row)">设置角色</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-row>
				<div class="pagination-container">
					<el-col :span="24">
						<el-pagination :current-page="queryParams.current" :page-sizes="[10, 20, 30, 50]"
							:page-size="queryParams.limit" :total="queryParams.total" layout="total, sizes, prev, pager, next, jumper"
							prev-text="上一页" next-text="下一页" background @size-change=" " @current-change=" " />
					</el-col>
				</div>
			</el-row>

			<!-- 新增用户弹窗 -->
			<el-dialog v-model="showAddPop" title="新增用户" width="500px">
				<addUser :UserRoles="Role.UserRoles" @close="setAddPop" @refresh="queryUserList" />
			</el-dialog>

			<!-- 修改信息弹窗 -->
			<el-dialog v-model="showUpdatePop" title="修改信息" width="500px">
				<updataAccount :UserInfo="UserInfo" @setUpdatePop="setUpdatePop" @refresh="queryUserList" />
			</el-dialog>

			<!-- 设置角色弹窗 -->
			<el-dialog v-model="showRolePop" title="修改角色" width="500px">
				<updateRole :UserInfo="UserInfo" :UserRoles="Role.UserRoles" @close="setRolePop" />
			</el-dialog>

			<!-- 修改状态弹窗 -->
			<el-dialog v-model="showStatePop" title="修改状态" width="500px">
				<updateStatepop :UserInfo="UserInfo" @closePop="setStatePop" @refresh="queryUserList" />
			</el-dialog>
		</el-main>
	</el-container>
</template>

<script lang="ts" setup>
//平台机构--机构机构通用---因为可能不同项目的机构表不同可能需要更改机构相关代码
export interface FormState {
	[x: string]: any; //动态添加属性
}
import { ElMessage, ElMessageBox } from 'element-plus';
import addUser from './organization/addUser.vue'
import updataAccount from './organization/updataAccount.vue'
import updateRole from './organization/updateRole.vue'
import updateStatepop from './organization/updateStatepop.vue'
import { storeToRefs } from 'pinia';
import { httpReqeustApi } from '/@/api/linxyun/base';
import { useUserInfo } from '/@/stores/userInfo';
const httpReqeust = httpReqeustApi();
const stores = useUserInfo();
const { userInfos } = storeToRefs(stores);
const data = reactive({
	seachParms: {
		// 机构id
		CustomerID: '',
		UserName: '',
	},
	// 机构列表
	options: [],
	listLoading: false,
	tableList: <FormState>[],
	queryParams: {
		current: 1,
		limit: 20,
		total: 0,
	},
	Role: {
		UserRoles: [] as any[],
		OtherRoles: [] as any[],
	},
	UserInfo: {
		UserID: '',
		UserName: '',
		TelNo: '',
		Email: '',
		RoleCodes: ''
	},
	showAddPop: false,
	// 是否展示修改信息弹窗
	showUpdatePop: false,
	// 是否显示修改角色弹窗
	showRolePop: false,
	// 是否显示修改状态弹窗
	showStatePop:false,
	// true 平台 ，false机构
	isCustomer:false,
});
const { seachParms, options, listLoading, tableList,
	showUpdatePop, UserInfo, showRolePop,showStatePop,
	queryParams, Role, showAddPop,isCustomer } = toRefs(data);
// 如果是平台
if(BASE_API.CustomerType==0){
  isCustomer.value=true
}else{
  isCustomer.value=false
}
onMounted(async () => {
	queryInst();
	queryUserList()
});

/**
 * @description: 查询机构列表
 */
const queryInst = () => {
	httpReqeust
		.Post('query_inst', { limit: 200, current: 1 })
		.then((res: any) => {
			if ((res.code = '0000' && res.Records.length > 0)) {
				// 遍历机构列表将机构名称赋值到表格中
				options.value = res.Records;
				queryUserList();
			}
		})
		.catch((err) => { });
};

/**
 * @description: 查询机构管理员列表
 */
const queryUserList = (seachParms?: any) => {
	// 加载表格数据中
	// listLoading.value = true
	const params = {
		CustomerType: 1,
		...seachParms,
		current: queryParams.value.current,
		limit: queryParams.value.limit,
	};
	// 如果是平台那么查全部,反之
  if(isCustomer.value==false){
		params.CustomerID=userInfos.value?.CustomerID
	}
	
	
	httpReqeust.Post('queryUserList', params).then((res: any) => {
		if (res.code == '0000' && res.Records && res.Records.length >= 0) {
			tableList.value = res.Records;
			tableList.value.forEach((item: any, index: number) => {
				let { CustomerID } = item;
				options.value.forEach((element:any) => {
					if (CustomerID == element?.ins_id) {
						tableList.value[index].AgentName = element.ins_name;
					}
				});
			});
			queryParams.value.total = parseInt(res.TotalSize);

		} else {
			tableList.value = [];
		}
		queryRoles()
	});
};

const queryRoles = () => {
	httpReqeust.Post('queryRole').then((res: any) => {
		if (res.success) {
			Role.value.UserRoles = [];
			Role.value.OtherRoles = [];
			// 如果是平台机构管理
			if(isCustomer.value===true){
				for (const item of res.Records) {
				// 如果角色和当前子系统的id相等
				if (item.SubSys !== BASE_API.SubSysID) {
					Role.value.UserRoles.push(item);
				} else {
					Role.value.OtherRoles.push(item);
				}
			}
			}else{
				for (const item of res.Records) {
				// 如果角色和当前子系统的id相等
				if (item.SubSys == BASE_API.SubSysID) {
					Role.value.UserRoles.push(item);
				} else {
					Role.value.OtherRoles.push(item);
				}
			}
		  }
			for (let i = 0; i < tableList.value.length; i++) {
				let RoleName = '';
				const RoleCodes = [] as any[];
				for (let j = 0; j < Role.value.UserRoles.length; j++) {
					if (tableList.value[i].UserRoles.indexOf(Role.value.UserRoles[j].RoleCode) !== -1) {
						RoleName += Role.value.UserRoles[j].RoleName + ',';
						RoleCodes.push(Role.value.UserRoles[j].RoleCode);
					}
				}
				if (RoleName[RoleName.length - 1] === ',') {
					RoleName = RoleName.slice(0, RoleName.length - 1);
				}
				tableList.value[i]['RoleName'] = RoleName;
				tableList.value[i]['RoleCodes'] = RoleCodes;
				addUserStatus();
			}
		}
	});
};
/**
 * @description: 添加用户状态
 */
const addUserStatus = () => {
	tableList.value.forEach((item: any) => {
		switch (item.UserStatus) {
			case '0':
				item.UserStatus = '正常';
				break;
			case '3':
				item.UserStatus = '暂停';
				break;
			case '9':
				item.UserStatus = '注销';
				break;
		}
	});
};

/**
 * @description: 设置（打开关闭）新增用户弹窗
 */
const setAddPop = (value: boolean) => {
	data.showAddPop = value
}
/**
 * @description: 处理每页条数的变化
 */
const handleSizeChange = (size: number) => {
	queryParams.value.limit = size
	queryUserList()
}

/**
 * @description: 处理上下一页
 */
const handleCurrentChange = (current: number) => {
	queryParams.value.current = current
	queryUserList()
}
/**
 * @description: 设置（打开关闭）用户信息弹窗
 */
const setUpdatePop = (value: boolean, Userinfo?: any) => {
	data.showUpdatePop = value
	if (Userinfo) {
		UserInfo.value.UserID = Userinfo.UserID
		UserInfo.value.UserName = Userinfo.UserName
		UserInfo.value.TelNo = Userinfo.TelNo
		UserInfo.value.Email = Userinfo.Email
	}
}
/**
 * @description: 设置（打开关闭）角色修改弹窗
 */
const setRolePop = (value: boolean, Userinfo?: any) => {
	data.showRolePop = value
	if (Userinfo) {
		UserInfo.value.UserID = Userinfo.UserID
		UserInfo.value.RoleCodes = Userinfo.RoleCodes
	}
}

/**
 * @description: 设置（打开关闭）用户状态弹窗
 */
 const setStatePop =(value:boolean,Userinfo?:any)=>{
	data.showStatePop=value 
  if(Userinfo){
    UserInfo.value.UserID=Userinfo.UserID
  }
}
/**
 * @description: 删除用户
 */
 const deleteUser = (user:any) =>{
	ElMessageBox.confirm(
    '此操作将永久删除改用户，是否继续',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    sentDeleteReq(user)
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
/**
 * @description: 发送删除用户的请求
 */
 const sentDeleteReq =(param:any)=>{
	const finallyParam ={
		UserID:param.UserID,
    EntCode:param.EntCode,
    CustomerType:1,
    CustomerID:userInfos.value?.CustomerID,
	}
  httpReqeust.Post('deleteUser',finallyParam).then((result:any) => {
		if(result.msg === 'success' && result.code== '0000'){
			ElMessage({
		    type: 'success',
			  message: '删除成功',
		  });
			queryUserList()
		}else{
			ElMessage({
		    type: 'error',
			  message: '删除失败',
		  });
		}
	}).catch((err) => {
		ElMessage({
		  type: 'error',
			message: '删除失败',
		});
	});
}
</script>
